package org.canto.poss.instr.core.util;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Description: MDC工具类
 *
 * @author jsryin
 * @date 2024/12/13 8:01
 */
public class MdcUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(MdcUtils.class);

    public final static String TRACE_ID = "traceId";

    public static String getTraceId() {
        return MDC.get(TRACE_ID);
    }

    public static void setTraceId(String traceId) {
        MDC.put(TRACE_ID, traceId);
    }

    /**
     * 增加MDC信息 Callable
     *
     * @param callable
     * @param context  主线程MDCcontext
     * @param <T>
     * @return
     */
    public static <T> Callable<T> adapt(final Callable<T> callable, final Map<String, String> context) {
        return () -> {
            setMDCContextMap(context);
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    /**
     * 增加MDC信息 Runnable
     *
     * @param runnable
     * @param context  主线程MDCcontext
     * @return
     */
    public static Runnable adapt(final Runnable runnable, final Map<String, String> context) {
        return () -> {
            setMDCContextMap(context);
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }


    /**
     * 设置上下文MDC
     *
     * @param context 主线程context
     */
    public static void setMDCContextMap(final Map<String, String> context) {
        if (MapUtils.isEmpty(context) || StringUtils.isEmpty(context.get(TRACE_ID))) {
            setTraceId(RandomUtils.fastTraceId());
        } else {
            MDC.setContextMap(context);
        }
    }


}
